package com.qili.core.quartz.CustomQuartz;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.qili.entity.supplier.OaData;
import com.qili.entity.supplier.dto.OaReDTO;
import com.qili.entity.supplier.dto.OaReDataDTO;
import com.qili.redis.RedisService;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.ProjectNoticeServie;
import com.qili.service.supplier.OaDataService;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.util.BeanUtil;
import com.qili.util.DateUtil;
import com.qili.util.OaInfoUtil;
import lombok.extern.java.Log;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.security.spec.ECField;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Log
public class OadataJob implements Job {
    @Autowired
    SysUserService sys;
    @Autowired
    private OaDataService oaDataService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    ProjectNoticeServie projectNoticeServie;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    BaseCompanyService baseCompanyService;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("oajob：启动任务=======================");
        log.info("oajob=========================================");
        run();
        System.out.println("oajob下次执行时间=====" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(context.getNextFireTime()) + "==============");
    }

    public void run() {
        saveOadata();
    }

    public void saveOadata() {

        log.info("oajob=======开始==================================");
        String lockkey = "oaData_key";
        String uuId = IdUtil.simpleUUID();
        try {
            lock(lockkey,uuId);
            JSONObject paraObj = new JSONObject();
            OaReDTO oaData = OaInfoUtil.queryOa(paraObj.toJSONString());
            List<OaReDataDTO> list = oaData.getDatas();
            OaData oaData1 = new OaData();
            oaDataService.delete(oaData1);
            for(int x = 0;x<list.size();x++){
                OaReDataDTO oaReDataDTO = list.get(x);
                OaData newOaDate=new OaData();
                BeanUtil.copyNotNullBean(oaReDataDTO,newOaDate);
                newOaDate.setOaId(newOaDate.getId());
                newOaDate.setId(null);
                // 计算费率 监理回款额 咨询回款额 检测回款额
                if (!StringUtils.isEmpty(newOaDate.getSshtje()) && !StringUtils.isEmpty(newOaDate.getSsxmtze())){
                    try {
                        // 等同于合同额/投资金额
                        BigDecimal hte = new BigDecimal(newOaDate.getSshtje());
                        BigDecimal tzje = new BigDecimal(newOaDate.getSsxmtze());
                        // 保留两位小数，转换为%
                        BigDecimal fl = hte.divide(tzje,2,BigDecimal.ROUND_HALF_UP);
                        String sfl = fl.multiply(new BigDecimal("100")).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
                        newOaDate.setFl(sfl);
                    }catch (Exception e){

                    }
                }
                if (!StringUtils.isEmpty(newOaDate.getJlf()) && !StringUtils.isEmpty(newOaDate.getSshtje()) && !StringUtils.isEmpty(newOaDate.getYhkje())){
                    try {
                        // 等于监理合同额/合同金额*回款总额
                        newOaDate.setJlmoney(((new BigDecimal(newOaDate.getJlf()).divide(new BigDecimal(newOaDate.getSshtje()), 2)).multiply(new BigDecimal(newOaDate.getYhkje()))).toString());
                    }catch (Exception e){
                        System.out.println("监理费出错了");
                    }
                }
                if (!StringUtils.isEmpty(newOaDate.getZxf()) && !StringUtils.isEmpty(newOaDate.getSshtje()) && !StringUtils.isEmpty(newOaDate.getYhkje())){
                    try {
                        // 等于监理合同额/合同金额*回款总额
                        newOaDate.setZxmoney(((new BigDecimal(newOaDate.getZxf()).divide(new BigDecimal(newOaDate.getSshtje()), 2)).multiply(new BigDecimal(newOaDate.getYhkje()))).toString());
                    }catch (Exception e){
                        System.out.println("咨询费出错了");
                    }
                }
                if (!StringUtils.isEmpty(newOaDate.getJcf()) && !StringUtils.isEmpty(newOaDate.getSshtje()) && !StringUtils.isEmpty(newOaDate.getYhkje())){
                    try {
                        // 等于监理合同额/合同金额*回款总额
                        newOaDate.setJcmoney(((new BigDecimal(newOaDate.getJcf()).divide(new BigDecimal(newOaDate.getSshtje()), 2)).multiply(new BigDecimal(newOaDate.getYhkje()))).toString());
                    }catch (Exception e){
                        System.out.println("检测费出错了");
                    }
                }
                // 设置创建时间
                newOaDate.setCreateDate(DateUtil.getCurrentDateString());
                oaDataService.insert(newOaDate);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }finally {
            unlock(lockkey,uuId);
        }
    }

    public void lock(String key, String uuId) {
        for (; ; ) {

            System.out.println(redisService);
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            }else {
                throw new RuntimeException("已经存在的执行程序...");
            }
        }
    }

    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }
}
